/*
 * @Date: 2025-11-05 20:14:35
 * @LastEditors: xialang333@gamil.com
 * @LastEditTime: 2025-11-05 20:47:32
 */
// pkg/utils.go - 工具函数模块
package pkg

import (
	"bufio"
	"database/sql"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	_ "modernc.org/sqlite"
)

// HostInfo 存储主机信息
type HostInfo struct {
	ID       int    `json:"id"`
	IP       string `json:"ip"`
	Port     int    `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	RootPass string `json:"root_pass"` // root密码
}

// TaskResult 存储任务执行结果
type TaskResult struct {
	IP        string `json:"ip"`
	Command   string `json:"command"`
	Output    string `json:"output"`
	Error     string `json:"error"`
	Success   bool   `json:"success"`
	Timestamp string `json:"timestamp"`
}

// Config 配置信息
type Config struct {
	AutoConfirm bool `json:"auto_confirm"`
}

// RemoteControlTool 远程控制工具
type RemoteControlTool struct {
	DB      *sql.DB
	config  Config
	key     []byte // 加密密钥
	scanner *bufio.Scanner
	LogFile *os.File
}

// NewRemoteControlTool 创建新的远程控制工具实例
func NewRemoteControlTool() (*RemoteControlTool, error) {
	os.MkdirAll("conf", 0755)
	os.MkdirAll("logs", 0755)

	dbPath := filepath.Join("conf", "remote_control.db")
	db, err := sql.Open("sqlite", dbPath)
	if err != nil {
		return nil, err
	}

	_, err = db.Exec(`CREATE TABLE IF NOT EXISTS hosts (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		ip TEXT NOT NULL,
		port INTEGER DEFAULT 22,
		user TEXT NOT NULL,
		password TEXT NOT NULL,
		root_pass TEXT
	)`)
	if err != nil {
		return nil, err
	}


	keyPath := filepath.Join("conf", "key.dat")
	key, err := loadOrGenerateKey(keyPath)
	if err != nil {
		return nil, err
	}

	logFilePath := filepath.Join("logs", "remote_control.log")
	logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, err
	}

	config := loadConfig()

	tool := &RemoteControlTool{
		DB:      db,
		config:  config,
		key:     key,
		scanner: bufio.NewScanner(os.Stdin),
		LogFile: logFile,
	}

	return tool, nil
}

// ReadInput 读取用户输入
func (rct *RemoteControlTool) ReadInput(prompt string) string {
	fmt.Print(prompt)
	rct.scanner.Scan()
	return strings.TrimSpace(rct.scanner.Text())
}




